import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import Cookies from 'js-cookie'
import http from '@/utils/http'
import { isURL } from '@/utils/validate'

Vue.use(Router)

// 页面路由(独立页面)
const pageRoutes = [
  { path: '/404', component: () => import('@/views/pages/404'), name: '404', meta: { title: '404未找到' } },
  { path: '/login', component: () => import('@/views/pages/login'), name: 'login', meta: { title: '登录' } }
]

// 模块路由(需嵌套上左右整体布局)
const moduleRoutes = {
  path: '/',
  component: () => import('@/views/main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    { path: '/home', component: () => import('@/views/modules/home'), name: 'home', meta: { title: '首页' } }
  ],
  beforeEnter (to, from, next) {
    if (!Cookies.get('token')) {
      store.commit('clearLoginInfo')
      next({ name: 'login', replace: true })
    } else {
      next()
    }
  }
}
const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  routes: pageRoutes.concat(moduleRoutes)
})

router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 如果, 已经添加或者当前路由为页面路由, 可直接访问
  // 否则, 获取菜单列表, 添加并全局变量保存
  if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] || fnCurrentRouteIsPageRoute(to, pageRoutes)) {
    next()
  } else {
    http.get('/sys/menu/nav').then(({data}) => {
      if (data && data.code === 0) {
        window.SITE_CONFIG['menuList'] = data.data
        fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
        next({ ...to, replace: true })
      } else {
        window.SITE_CONFIG['menuList'] = []
        next()
      }
    }).catch((e) => {
      router.push({ name: 'login' })
    })
  }
})

/**
 * 判断当前路由是否为页面路由
 * @param {*} route 当前路由
 * @param {*} pageRoutes 页面路由
 */
function fnCurrentRouteIsPageRoute (route, pageRoutes = []) {
  var temp = []
  for (var i = 0; i < pageRoutes.length; i++) {
    if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) {
      temp = temp.concat(pageRoutes[i].children)
    } else if (route.path === pageRoutes[i].path) {
      return true
    }
  }
  return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      var route = {
        path: '',
        component: null,
        name: '',
        meta: {
          menuId: menuList[i].id,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      if (isURL(menuList[i].url)) {
        // 通过iframe展示, url以http[s]://开头
        route['path'] = `i-${menuList[i].id}`
        route['name'] = `i-${menuList[i].id}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        // 通过component展示
        menuList[i].url = menuList[i].url.replace(/^\//, '').replace(/_/g, '-')
        route['path'] = menuList[i].url.replace('/', '-')
        route['name'] = menuList[i].url.replace('/', '-')
        try {
          ((i) => {
            route['component'] = () => import(`@/views/modules/${menuList[i].url}`)
          })(i)
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    moduleRoutes.name = 'main-dynamic'
    moduleRoutes.children = routes
    router.addRoutes([
      moduleRoutes,
      { path: '*', redirect: { name: '404' } }
    ])
    window.SITE_CONFIG['dynamicMenuRoutes'] = moduleRoutes.children
    window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
  }
}

export default router
